package cn.edu.tju.fctl.util;

import cn.edu.tju.fctl.entities.User;
import cn.edu.tju.fctl.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by liutong on 15/12/16.
 */
@Component
public class UserRealm extends AuthorizingRealm {
    private static final String SPLIT = ","; // 分隔符
    IUserService userService;

    public String getName() {
        return "UserRealm";
    }

    public boolean supports(AuthenticationToken token) {
        //仅支持UsernamePasswordToken类型的Token
        return token instanceof UsernamePasswordToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String)authenticationToken.getPrincipal();  //得到用户名
        String password = new String((char[]) authenticationToken.getCredentials()); //得到密码

        User user = userService.findByNumber(username);

        if(user == null) {
            throw new UnknownAccountException(); //如果用户名错误
        }
        if(!user.getPwd().equals(password)) {
            throw new IncorrectCredentialsException(); //如果密码错误
        }
        ShiroUtil.setUser(user);
        //如果身份认证验证成功，返回一个AuthenticationInfo实现；
        return new SimpleAuthenticationInfo(username, password, getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Set<String> roles = new HashSet<String>();
        String usernames = (String)principalCollection.getPrimaryPrincipal();
        User user = userService.findByNumber(usernames);
        String[] userRoles = user.getRole().split(SPLIT);
        for (String r : userRoles){
            roles.add(r);
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
        info.setRoles(roles);

        return info;
    }

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
